package com.example.administrator.hqq.activity.group;

import android.app.AlertDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.example.administrator.hqq.R;
import com.example.administrator.hqq.View.alertview.AlertViewFactory;
import com.example.administrator.hqq.base.MyActivity;
import com.example.administrator.hqq.bean.Complain;
import com.example.administrator.hqq.bean.JoinIntrrductionBean;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;
import com.example.administrator.hqq.utils.HintWordsUtils;
import com.example.administrator.hqq.utils.SketchTextWatcher;
import com.google.gson.Gson;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;
import okhttp3.Call;

public class JoinGroupActivity extends MyActivity {

    @BindView(R.id.join_group)
    ImageView joinGroup;
    @BindView(R.id.group_title)
    TextView groupTitle;
    @BindView(R.id.group_number)
    TextView groupNumber;
    @BindView(R.id.group_introduce)
    TextView groupIntroduce;
    @BindView(R.id.group_question1)
    TextView groupQuestion1;
    @BindView(R.id.answer1_et)
    EditText answer1Et;
    @BindView(R.id.group_question2)
    TextView groupQuestion2;
    @BindView(R.id.answer2_et)
    EditText answer2Et;
    @BindView(R.id.group_people)
    TextView groupPeople;
    @BindView(R.id.join)
    Button join;
    @BindView(R.id.inform_auto)
    AutoLinearLayout informAuto;
    @BindView(R.id.q1)
    TextView q1;
    @BindView(R.id.question1)
    AutoLinearLayout question1;
    @BindView(R.id.group_join_view1)
    View groupJoinView1;
    @BindView(R.id.anchor1)
    AutoLinearLayout anchor1;
    @BindView(R.id.group_join_view2)
    View groupJoinView2;
    @BindView(R.id.question2)
    AutoLinearLayout question2;
    @BindView(R.id.group_join_view3)
    View groupJoinView3;
    @BindView(R.id.anchor2)
    AutoLinearLayout anchor2;
    private String TAG = this.getClass().getSimpleName();
    private Boolean aBoolean;
    private AlertDialog showReportAlertView;
    private JoinIntrrductionBean joinIntrrductionBean;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_join_group);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initdata();
        initview();
    }

    private void initview() {
        SketchTextWatcher sketchTextWatcher = new SketchTextWatcher(answer1Et, 54);
        answer1Et.addTextChangedListener(sketchTextWatcher);
        SketchTextWatcher sketchTextWatcher1 = new SketchTextWatcher(answer2Et, 54);
        answer2Et.addTextChangedListener(sketchTextWatcher1);
    }

    private void initdata() {
        OkHttpUtils.get().url(UrlFactory.getJoinIntroduction())
                .addParams(LoongsConfig.group_id, getIntent().getStringExtra(LoongsConfig.group_id))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: " + e.getMessage());
                ToastUtils.showShort("数据访问错误");
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "onResponse: " + response);
                Gson gson = new Gson();
                join.setVisibility(View.VISIBLE);
                joinIntrrductionBean = gson.fromJson(response, JoinIntrrductionBean.class);
                if (joinIntrrductionBean != null && joinIntrrductionBean.getCode() == 200) {
                    aBoolean = false;
                    join.setText("申请加群");
                    groupQuestion1.setText(joinIntrrductionBean.getQuestion_1());
                    question1.setVisibility(View.VISIBLE);
                    anchor1.setVisibility(View.VISIBLE);
                    groupJoinView1.setVisibility(View.VISIBLE);
                    if (joinIntrrductionBean.getQuestion_amount() == 2&&!TextUtils.isEmpty(joinIntrrductionBean.getQuestion_2())) {
                        question2.setVisibility(View.VISIBLE);
                        anchor2.setVisibility(View.VISIBLE);
                        groupJoinView1.setVisibility(View.VISIBLE);
                        groupJoinView2.setVisibility(View.VISIBLE);
                        groupJoinView3.setVisibility(View.VISIBLE);
                        groupQuestion2.setText(joinIntrrductionBean.getQuestion_2());
                    }
                    setMessage(joinIntrrductionBean);
                } else if (joinIntrrductionBean.getCode() == 201) {
                    aBoolean = true;
                    question1.setVisibility(View.VISIBLE);
                    groupJoinView1.setVisibility(View.GONE);
                    question2.setVisibility(View.GONE);
                    anchor2.setVisibility(View.GONE);
                    anchor1.setVisibility(View.GONE);
                    q1.setText("该群暂无进群问题");
                    join.setText("加入群聊");
                    setMessage(joinIntrrductionBean);

                }
            }
        });
    }

    private void setMessage(JoinIntrrductionBean joinIntrrductionBean) {
        groupTitle.setText(joinIntrrductionBean.getTitle());
        groupNumber.setText(joinIntrrductionBean.getNumber());
        groupPeople.setText(joinIntrrductionBean.getMember_amount() + "/" + joinIntrrductionBean.getMax_member());
        if (joinIntrrductionBean.getIntroduction() != null&&!TextUtils.isEmpty(joinIntrrductionBean.getIntroduction())) {
            groupIntroduce.setText(joinIntrrductionBean.getIntroduction());
        }
        Glide.with(this).load(joinIntrrductionBean.getUrl()).centerCrop().into(joinGroup);
    }


    private void applyJoin() {
        if (joinIntrrductionBean.getQuestion_amount() == 2) {
            if (TextUtils.isEmpty(answer1Et.getText()) || TextUtils.isEmpty(answer2Et.getText())) {
                ToastUtils.showShort("请把问题补充完整");
                return;
            }
        } else {
            if (TextUtils.isEmpty(answer1Et.getText())) {
                ToastUtils.showShort("请把问题补充完整");
                return;
            }
        }
        String s = TextUtils.isEmpty(answer2Et.getText().toString()) ? "" : "/*@*/" + answer2Et.getText().toString();
        String s1 = answer1Et.getText().toString() + s;
        OkHttpUtils.get().url(UrlFactory.getJoinApply())
                .addParams(LoongsConfig.group_id, getIntent().getStringExtra(LoongsConfig.group_id))
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.answer, s1)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: " + e);
                ToastUtils.showShort("服务器访问失败");
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    HintWordsUtils.showMarkeWords(jsonObject.getInt(LoongsConfig.code), jsonObject.getString(LoongsConfig.description));
                    if (jsonObject.getInt("code") == 200) {
                        ToastUtils.showShort("申请已提交,请耐心等待");
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void joinChat() {
        OkHttpUtils.get().url(UrlFactory.getJoin())
                .addParams(LoongsConfig.group_id, getIntent().getStringExtra(LoongsConfig.group_id))
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: " + e);
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    HintWordsUtils.showMarkeWords(jsonObject.getInt(LoongsConfig.code),jsonObject.getString(LoongsConfig.description));
                    if (jsonObject.getInt(LoongsConfig.code) == 200) {
                        Complain complain = new Complain(Complain.Type.JOIN_GROUP, "");
                        EventBus.getDefault().post(complain);
                        LoongsConfig.getUsersIdSPUtils().put(LoongsConfig.Conversation.ChatConversationType, LoongsConfig.Conversation.GROUP);
                        LoongsConfig.getUsersIdSPUtils().put(LoongsConfig.Conversation.ConversationID, getIntent().getStringExtra(LoongsConfig.group_id));
                        RongIM.getInstance().startConversation(JoinGroupActivity.this, Conversation.ConversationType.GROUP, getIntent().getStringExtra(LoongsConfig.group_id), "话圈圈");
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @OnClick({R.id.join_group, R.id.join, R.id.inform_auto})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.join_group:
                finish();
                break;
            case R.id.join:
                if (aBoolean) {
                    joinChat();
                } else {
                    applyJoin();
                }
                break;
            case R.id.inform_auto:
                List<String> strings = new ArrayList<>();
                for (String s : this.getResources().getStringArray(R.array.forum_report)) {
                    strings.add(s);
                }
                showReportAlertView = AlertViewFactory.getInstance().getShowReportAlertView(this, strings, new AlertViewFactory.ReportOnClickListener() {
                    @Override
                    public void submit(int position) {
                        Log.e(TAG, "submit: " + position);
                        showReportAlertView.cancel();
                        reportGroup(position);
                    }
                });
                break;
        }
    }

    /**
     * 举报群聊
     *
     * @param position 举报项的下标
     */
    private void reportGroup(int position) {
        OkHttpUtils.get().url(UrlFactory.ReportForum())
                .addParams(LoongsConfig.id, getIntent().getStringExtra(LoongsConfig.group_id))
                .addParams(LoongsConfig.type, "3")
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.reason_id, position + 401 + "")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "举报群聊onError: " + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "举报群聊onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    HintWordsUtils.showMarkeWords(jsonObject.getInt(LoongsConfig.code), jsonObject.getString(LoongsConfig.description));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(String s) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected String getActivityName() {
        return this.getClass().getSimpleName();
    }
}
